package cc.rengu.igas.cops.core.service.trans.payment;

import cc.rengu.igas.cops.common.enums.RespCodeEnum;
import cc.rengu.igas.cops.core.service.base.ManageService;
import cc.rengu.igas.cops.facade.request.ResetPayPasswdRequest;
import cc.rengu.igas.share.core.model.UserInfo;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SignAcctInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.SignAcctInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.common.enums.PinTypeEnum;
import cc.rengu.oltp.service.common.enums.SmsTypeEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.HsmService;
import cc.rengu.oltp.service.realize.SmsService;
import cc.rengu.oltp.service.realize.impl.HsmServiceImpl;
import cc.rengu.oltp.service.realize.impl.SmsServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import com.alibaba.fastjson.JSON;

import java.util.List;
import java.util.stream.Collectors;

public class CopsResetPayPasswdService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        ResetPayPasswdRequest resetPayPasswdRequest = new ResetPayPasswdRequest();
        ConvertUtil.convertOutput(resetPayPasswdRequest);
        return resetPayPasswdRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        ResetPayPasswdRequest resetPayPasswdRequest = new ResetPayPasswdRequest();
        ConvertUtil.convertOutput(resetPayPasswdRequest);

        String instId = resetPayPasswdRequest.getHeader().getInstId();
        String userId = resetPayPasswdRequest.getUserId();
        String txnMode = resetPayPasswdRequest.getTxnMode();
        String payAcctNo = resetPayPasswdRequest.getPayAcctNo();

        BizResponse<Object> bizResponse = new BizResponse<>();

        //获取用户
        UserService userService = new UserServiceImpl();
        UserInfo userInfo = JSON.parseObject(RedisUtil.hashGet(resetPayPasswdRequest.getHeader().getSession(), resetPayPasswdRequest.getHeader().getInstId() + resetPayPasswdRequest.getUserId()), UserInfo.class);
        if (null == userInfo) {
            rglog.error("获取用户信息失败!");
            throw new BizException(RespCodeEnum.USER_NOT_LOGIN_OR_SESSION_IS_EXPIRED.getRespCode(), RespCodeEnum.USER_NOT_LOGIN_OR_SESSION_IS_EXPIRED.getRespDesc());
        }
        String signInst = userService.getUserSignInst();
        //查询短信验证码表（T_P_SMS_INFO）,校验短信验证码字段（authCode）,修改密码与设置密码使用短信模板不一致需分开校验短信验证码
        SmsService smsService = new SmsServiceImpl();

        if ("01".equals(txnMode)) {

            smsService.verifySmsCode(instId, SmsTypeEnum.SET_PASSWORD.getSmsType(), resetPayPasswdRequest.getSmsCode(), resetPayPasswdRequest.getSmsVerifySeqNum());

            //检测上送的手机号和用户的签约手机号是否一致
            if (!userInfo.getMobileNo().equals(resetPayPasswdRequest.getPhoneNo())) {
                rglog.info("上送手机号和用户签约手机号不一致，userMobile:<{}>, reqeustMobile:<{}>",
                        userInfo.getMobileNo(), resetPayPasswdRequest.getPhoneNo());
                throw new BizException(RespCodeEnum.MOBILE_DIFERENT.getRespCode(), RespCodeEnum.MOBILE_DIFERENT.getRespDesc());
            }

            //修改支付密码为新支付密码
            HsmService hsmService = new HsmServiceImpl();
            String passwdPin = hsmService.hsmTranslatePin(instId, "", "", userInfo.getTransPasswordSalt(), userInfo.getTransPasswordSalt(), resetPayPasswdRequest.getPassword());
            String newTransPassword = hsmService.hsmGeneratePinOffset(instId, "", "", userInfo.getTransPasswordSalt(), PinTypeEnum.DIGITAL, passwdPin);
            userInfo.setTransPassword(newTransPassword);
//            OpmsUserInfoMapper updateUerInfoMapper = new OpmsUserInfoMapperImpl();
//            int insterTransPasswordResult = updateUerInfoMapper.updateOpmsSysUserInfo(userInfo);
//            if (insterTransPasswordResult != 0) {
//                rglog.info("更新收银台用户支付支付密码信息失败,userId:<{}>", userId);
//                throw new BizException(RespCodeEnum.MCHNT_AMT_OVER.getRespCode(), RespCodeEnum.MCHNT_AMT_OVER.getRespDesc());
//            } else {
//                rglog.debug("设置收银台用户信息表用户支付密码成,userId:<{}>", userId);
//            }

            //设置响应
            bizResponse.setRspSysId(AppParamConstant.SYS_ID);
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            return bizResponse;
        }
        //交易类别 02-密码重置
        else if ("02".equals(txnMode)) {

            smsService.verifySmsCode(instId, SmsTypeEnum.RESET_PASSWORD.getSmsType(), resetPayPasswdRequest.getSmsCode(), resetPayPasswdRequest.getSmsVerifySeqNum());

            //检测上送的手机号和用户的签约手机号是否一致
            if (!userInfo.getMobileNo().equals(resetPayPasswdRequest.getPhoneNo())) {
                rglog.info("上送手机号和用户签约手机号不一致，userMobile:<{}>, reqeustMobile:<{}>",
                        userInfo.getMobileNo(), resetPayPasswdRequest.getPlatMchntNo());
                throw new BizException(RespCodeEnum.MOBILE_DIFERENT.getRespCode(), RespCodeEnum.MOBILE_DIFERENT.getRespDesc());
            }

            //查询用户签约信息表（T_P_SIGN_ACCT_INFO）获取身份验证交易结果状态
            SignAcctInfoMapper signAcctInfoMapper = new SignAcctInfoMapperImpl();
            //查询用户当前签约主体下所有的签约信息
            List<SignAcctInfo> signAcctInfos = signAcctInfoMapper.selectSignAcctInfoBySignTyUserId(instId, userId, signInst);
            if (signAcctInfos != null) {
                //过滤签约状态为正常和本账号的签约信息
                signAcctInfos = signAcctInfos.stream().filter(item -> AppParamConstant.YES.equals(item.getSignStatus())
                        && payAcctNo.equals(item.getSignAcctNo())).collect(Collectors.toList());
            }
            if (null == signAcctInfos || signAcctInfos.isEmpty()) {
                rglog.info("用户不存在签约信息，instId:<{}>,signInst:<{}>,signAcctNo:<{}>", instId, signInst, payAcctNo);
                throw new BizException(RespCodeEnum.GET_SIGN_INFO_ERROR.getRespCode(), RespCodeEnum.GET_SIGN_INFO_ERROR.getRespDesc());
            }

            //校验证件号码
            SignAcctInfo signAcctInfo = signAcctInfos.get(0);
            if (signAcctInfo.getCertType().equals(resetPayPasswdRequest.getCertType()) && !signAcctInfo.getCertNo().equals(resetPayPasswdRequest.getCertNo())) {
                rglog.info("用户证件信息不匹配,exitCertType:<{}>,exitCertNo:<{}>,reqCertType:<{}>,reqCertNo:<{}>",
                        signAcctInfo.getCertType(), signAcctInfo.getCertNo(), resetPayPasswdRequest.getCertType(), resetPayPasswdRequest.getCertNo());
                throw new BizException(RespCodeEnum.USER_INFO_MISMATCH.getRespCode(), RespCodeEnum.USER_INFO_MISMATCH.getRespDesc());
            }

            //设置支付密码
            HsmService hsmService = new HsmServiceImpl();
            String passwdPin = hsmService.hsmTranslatePin(instId, "", "", userInfo.getTransPasswordSalt(), userInfo.getTransPasswordSalt(), resetPayPasswdRequest.getPassword());
            String pwdOffset = hsmService.hsmGeneratePinOffset(instId, "", "", userInfo.getTransPasswordSalt(), PinTypeEnum.DIGITAL, passwdPin);
            userInfo.setTransPassword(pwdOffset);
            userInfo.setTransPasswordErrorTimes(0);
//            userInfo.setLastPayDate(DateUtil.getCurrentDate());
//            OpmsUserInfoMapper updateUserInfoMapper = new OpmsUserInfoMapperImpl();
//            int insterTransPasswordResult = updateUserInfoMapper.updateOpmsSysUserInfo(userInfo);
//            if (insterTransPasswordResult != 0) {
//                rglog.info("更新收银台用户支付支付密码信息失败,userId:<{}>", userId);
//                throw new BizException(RespCodeEnum.USER_SET_PASSWORD_ERROR.getRespCode(), RespCodeEnum.USER_SET_PASSWORD_ERROR.getRespDesc());
//            } else {
//                rglog.debug("设置收银台用户信息表用户支付密码成功:userId:<{}>", userId);
//            }

            //设置响应
            bizResponse.setRspSysId(AppParamConstant.SYS_ID);
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            return bizResponse;
        } else {
            rglog.info("无法识别的交易类别,txnMode:<{}>", txnMode);
            throw new BizException(RespCodeEnum.NOT_SURP_TRANS_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SURP_TRANS_TYPE_ERROR.getRespDesc());
        }
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {

    }
}
